package com.yangguang.huahui.ui.fragments;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.yangguang.huahui.Config;
import com.yangguang.huahui.R;
import com.yangguang.huahui.baseadapter.BaseQuickAdapter;
import com.yangguang.huahui.baseadapter.BaseViewHolder;
import com.yangguang.huahui.easemob.AppHelper;
import com.yangguang.huahui.entity.ChatMessage;
import com.yangguang.huahui.entity.DataInfo;
import com.yangguang.huahui.mvp.presenter.ChatMessagePresenter;
import com.yangguang.huahui.mvp.view.ChatMessageView;
import com.yangguang.huahui.ui.activitys.ChatActivity;
import com.yangguang.huahui.ui.activitys.DetailActivity;
import com.yangguang.huahui.utils.EmojiToText;
import com.yangguang.huahui.utils.ImageLoader;
import com.hyphenate.easeui.utils.TimeUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.yangguang.huahui.app.App.context;

/**
 * Created by Administrator on 2017/3/15.
 */

public class ChatMessageFragment extends BaseMvpFragment<ChatMessageView, ChatMessagePresenter> implements ChatMessageView {
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    ChatMessageAdapter mAdapter;
    LinearLayoutManager layoutManager;
    private List<ChatMessage.ListBean> chatList = new ArrayList<>();

    //接收消息监听
    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                AppHelper.getInstance().getNotifier().onNewMsg(message);
            }
            fetchData();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {

        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {}
    };

    @Override
    protected int initLayoutId() {
        return R.layout.frag_message;
    }

    @Override
    protected void initView() {
        layoutManager = new LinearLayoutManager(mActivity);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new ChatMessageAdapter(R.layout.other_msg_list_item, chatList);
        mRecyclerView.setAdapter(mAdapter);
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }


    @Override
    protected void initData() {

    }

    @Override
    public void onSuccess(ChatMessage chatMessage) {
        if (chatMessage.getList() != null) {
            chatList = chatMessage.getList();
        }
        mAdapter.setNewData(chatList);
    }

    @Override
    public void onError() {

    }

    @Override
    protected ChatMessagePresenter initPresenter() {
        return new ChatMessagePresenter();
    }

    @Override
    protected void fetchData() {
        if (mPresenter == null) return;
        mPresenter.getMsgList(DataInfo.TOKEN);
    }

    public static class ChatMessageAdapter extends BaseQuickAdapter<ChatMessage.ListBean> {

        public ChatMessageAdapter(int layoutResId, List<ChatMessage.ListBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final ChatMessage.ListBean item) {
            ImageLoader.loadCircle(context, item.getTo_icon(), (ImageView) helper.getView(R.id.iv_head));
            helper.setText(R.id.tv_name, item.getTo_name().replaceAll("\\[.{2,3}\\]", "[表情]"));
            helper.setText(R.id.tv_content, EmojiToText.addSmileySpans(context, item.getMsg()));
            helper.setText(R.id.tv_time,
                    TimeUtil.getChatTime(Long.parseLong(item.getCreatetime() + "000")));
            int unreadNum = 0;
            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(item.getTo_uid());
            //未读消息
            if (conversation != null && conversation.getUnreadMsgCount() != 0) {
                unreadNum = conversation.getUnreadMsgCount();
            }
            TextView textView = helper.getView(R.id.iv_weidu);
            if (unreadNum > 0) {
                textView.setVisibility(View.VISIBLE);
                if (unreadNum > 99) {
                    textView.setText(99 + "+");
                } else {
                    textView.setText(unreadNum + "");
                }
            } else {
                textView.setVisibility(View.GONE);
            }

            helper.setOnClickListener(R.id.iv_head, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mContext.startActivity(new Intent(mContext, DetailActivity.class)
                            .putExtra("webUrl", Config.PERSON_INFO)
                            .putExtra("id", item.getTo_uid())
                            .putExtra("type", 50));
                }
            });

            helper.setOnClickListener(R.id.view_msg, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(item.getFor_uid());
                    if (conversation != null) {
                        //指定会话消息未读数清零
                        conversation.markAllMessagesAsRead();
                    }
                    mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("userId", item.getTo_uid()));
                }
            });
        }
    }
}
